import React, { useEffect, useState } from "react";
import { View, Swiper, SwiperItem, Image, Text } from "@tarojs/components";
import Taro, { useReachBottom } from "@tarojs/taro";

const Home = () => {
  // 列表
  const [list, setList] = useState([]);
  const [_page, set_page] = useState(1);
  const [isFinish, setIsFinish] = useState(false);
  // 轮播
  const [banners, setBanners] = useState([]);
  // 导航菜单
  const [menus, setMenus] = useState([]);

  const fetchList = async () => {
    const resp = await Taro.request({
      url: "http://localhost:3000/list",
      data: {
        _page: _page,
      },
    });
    if (resp.data.length) {
      setList([...list, ...resp.data]);
      set_page(_page + 1);
    } else {
      setIsFinish(true);
    }
  };

  const fetchData = async () => {
    const [data2, data3] = await Promise.all([
      Taro.request({ url: "http://localhost:3000/banners" }),
      Taro.request({ url: "http://localhost:3000/menuList" }),
    ]);
    setBanners(data2.data);
    setMenus(data3.data);
  };

  const goToDetail = (v) => {
    Taro.navigateTo({
      url: "/pages/detail/index?id=" + v.id,
    });
  };

  // 上拉触底钩子函数 hooks
  useReachBottom(() => {
    if (isFinish) return;
    fetchList();
  });

  useEffect(() => {
    fetchData();
    fetchList();
  }, []);
  if (list.length === 0 || banners.length === 0 || menus === 0) {
    return <View>数据加载中...</View>;
  }
  return (
    <View className="home">
      {/* 轮播 */}
      <Swiper className="swiper">
        {banners.map((v, i) => {
          return (
            <SwiperItem key={i} className="swiper-item">
              <Image src={v} className="banner"></Image>
            </SwiperItem>
          );
        })}
      </Swiper>
      {/* 导航菜单 */}
      <View className="menu">
        {menus.map((v, i) => {
          return (
            <View key={i} className="menu-item">
              <Image src={v.image}></Image>
              <Text>{v.name}</Text>
            </View>
          );
        })}
      </View>
      {/* 列表 */}
      <View className="list">
        {list.map((v, i) => {
          return (
            <View className="list-item" key={i} onClick={() => goToDetail(v)}>
              <View className="left">
                <Image src={v.image}></Image>
              </View>
              <View className="right">
                <Text>{v.title}</Text>
                <Text>{v.desc}</Text>
                <Text className="price">￥：{v.price}</Text>
              </View>
            </View>
          );
        })}
      </View>
      {isFinish && <View className="not-data">没有更多数据了</View>}
    </View>
  );
};

export default Home;
